//
//  GreenHuaViewController.m
//  Qihuo
//
//  Created by Vencoo on 13-12-20.
//  Copyright (c) 2013年 Vencoo. All rights reserved.
//

#import "GreenHuaViewController.h"

@interface GreenHuaViewController ()
{
    NSMutableArray *checkIds;
    NSMutableArray *sendControls;
}
@end

@implementation GreenHuaViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    self.title = @"外围绿化巡检";
    [super viewDidLoad];
    
    NSURL *queryUrl = [NSURL URLWithString:getGrennHuaFloor];
    ASIFormDataRequest *obtainFloor = [ASIFormDataRequest requestWithURL:queryUrl];
    self.sendUrl = addGrennHua;
    [obtainFloor setPostValue:@"" forKey:@""];
    [obtainFloor startSynchronous];
    
    NSString *response = [obtainFloor responseString];
    NSDictionary *queryDic = [response JSONValue];
    NSArray *queryDataArr = [queryDic objectForKey:@"data"];
    NSLog(@"查询%@",queryDataArr);
    self.floorNames = [NSMutableArray array];
    checkIds = [NSMutableArray array];
    sendControls = [NSMutableArray array];
    [self.floorIds removeAllObjects];
    for (NSDictionary *dic in queryDataArr)
    {
        [self.floorNames addObject:[dic valueForKey:@"floorname"]];
        [self.floorIds addObject:[dic valueForKey:@"id"]];
        [self.sendFloorDatas addObject:@""];
        [self.xunJianCellInfos addObject:@{@"hidden":@"1",@"floorId":[dic valueForKey:@"id"] }];
    }
    
    [self initData];
    [self showUIWithArray:self.allShowDataArr andFloorId:@"1"];
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.myTableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}
- (void)initData
{
    NSDictionary *oneDic = @{@"checkId": @"1",@"checkName":@"灌木、乔木枝叶茂盛"};
    NSDictionary *twoDic = @{@"checkId": @"2",@"checkName":@"无虫害、无枯枝枯叶"};
    NSDictionary *threeDic = @{@"checkId": @"3",@"checkName":@"不露黄土"};
    NSDictionary *fourDic = @{@"checkId": @"4",@"checkName":@"绿地内无纸屑"};
    NSDictionary *fiveDic = @{@"checkId": @"5",@"checkName":@"无残枝败叶"};
    NSDictionary *sixDic = @{@"checkId": @"6",@"checkName":@"清洁整齐"};
    self.allShowDataArr = @[oneDic,twoDic,threeDic,fourDic,fiveDic,sixDic];
}
- (void)showUIWithArray:(NSArray *)array andFloorId:(NSString *)floorId
{
    [self clearAll];
    [checkIds removeAllObjects];
    [sendControls removeAllObjects];
    BOOL hasReserved = 0;
    self.floorIdQuanju = floorId;
    id receiveFloorObj = [self.sendFloorDatas objectAtIndex:[self.floorIds indexOfObjectss:self.floorIdQuanju]];
    if (![receiveFloorObj isKindOfClass:[NSString class]])
    {
        self.sendCheckDatas = [receiveFloorObj objectForKey:@"checkData"];
        hasReserved = 1;
    }

    for (int i = 0; i < array.count; i ++)
    {
        NSDictionary *dictionary = [array objectAtIndex:i];
        NSString *checkID = [dictionary valueForKey:@"checkId"];
        [checkIds addObject:checkID];
        NSString *checkName = [dictionary valueForKey:@"checkName"];
        [self addCheckNames:checkName];
        NSMutableArray *tfs = [NSMutableArray array];
        NSMutableArray *btns = [NSMutableArray array];
        if (hasReserved) {
            [self addVerticalChildName:@[@"正常",@"一般问题",@"严重问题"] andCheckId:checkID andResult:[[[receiveFloorObj objectForKey:@"checkData"]objectAtIndex:i]valueForKey:@"isNormal"]];
        }
        else
        {
            [self addVerticalChildName:@[@"正常",@"一般问题",@"严重问题"] andCheckId:checkID andResult:@""];
        }
        [btns addObject: self.selectBtnArr];
        
        UILabel *remarkLb = [UILabel new];
        remarkLb.text = @"备注：";
        remarkLb.font = [UIFont systemFontOfSize:25];
        CGSize mySz = [remarkLb.text sizeWithFont:remarkLb.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
        remarkLb.frame = CGRectMake(100, [[self.controlWillClears lastObject]frame].origin.y + [[self.controlWillClears lastObject]frame].size.height + interval111, mySz.width, mySz.height);
        [self.backScrollV addSubview:remarkLb];
        [self.controlWillClears addObject:remarkLb];
        
        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(190, remarkLb.frame.origin.y, 340, mySz.height)];
        tf.delegate = self;
        if (hasReserved)
        {
            tf.text = [[[[receiveFloorObj objectForKey:@"checkData"]objectAtIndex:i]valueForKey:@"checkRemark"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        tf.background = [UIImage imageNamed:@"输入框底"];
        [self.backScrollV addSubview:tf];
        [self.controlWillClears addObject:tf];
        [tfs addObject:tf];
        if (!hasReserved) {
            [self.sendCheckDatas addObject:@{@"checkId": checkID,@"isNormal":@"",@"checkRemark":@""}];
            [sendControls addObject:@{@"checkId": checkID,@"childControls":tfs,@"childBtns":self.selectBtnArr}];
        }
    }
    if (hasReserved)
    {
        [self addCommentKuang:[receiveFloorObj objectForKey:@"floorRemark"]];
    }
    else
    {
        [self addCommentKuang:@""];
    }
}
- (void)addCheckNames:(NSString*)string
{
    UILabel *checkNameLb = [UILabel new];
    checkNameLb.text = [NSString stringWithFormat:@"%@：",string];
    checkNameLb.font = [UIFont systemFontOfSize:26];
    CGSize mySize = [checkNameLb.text sizeWithFont:checkNameLb.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
    if (self.controlWillClears.count != 0)
    {
        checkNameLb.frame = CGRectMake(10, interval111+([[self.controlWillClears lastObject]frame].origin.y + [[self.controlWillClears lastObject]frame].size.height), mySize.width, mySize.height);
    }
    else
    {
        checkNameLb.frame = CGRectMake(10, 10, mySize.width, mySize.height);
    }
    [self.backScrollV addSubview:checkNameLb];
    [self.checkNameLbs addObject:checkNameLb];
    [self.controlWillClears addObject:checkNameLb];
}

- (void)addVerticalChildName:(NSArray *)array andCheckId:(NSString *)checkId andResult:(NSString *)result
{
    NSMutableArray *controlsArr = [NSMutableArray array];
    for (int i = 0; i<array.count; i++)
    {
        UIButton *roundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [roundBtn setImage:self.roundUnselect forState:UIControlStateNormal];
        [roundBtn addTarget:self action:@selector(selectBtns:) forControlEvents:UIControlEventTouchUpInside];
        if ([result isEqualToString:[NSString stringWithFormat:@"%i",i]])
        {
            [roundBtn setImage:self.roundSelect forState:UIControlStateNormal];
        }
        roundBtn.tag = 10+i;
        roundBtn.frame = CGRectMake([[self.checkNameLbs lastObject]frame].origin.x + 52, [[self.checkNameLbs lastObject]frame].origin.y  - 4 + ([[self.checkNameLbs lastObject]frame].size.height + 10)*(i+1) , self.roundUnselect.size.width, self.roundUnselect.size.height);
        [self.backScrollV addSubview:roundBtn];
        [self.controlWillClears addObject:roundBtn];
        [controlsArr addObject:roundBtn];
        
        UIImage *iconImage = [UIImage imageNamed:@""];
        switch (i)
        {
            case 0:
            {
                iconImage = [UIImage imageNamed:@"正常"];
            }
                break;
            case 1:
            {
                iconImage = [UIImage imageNamed:@"一般问题"];
            }
                break;
            case 2:
            {
                iconImage = [UIImage imageNamed:@"重大问题"];
            }
                break;
                
            default:
                break;
        }
        
        UIImageView *iconView = [[UIImageView alloc]initWithImage:iconImage];
        [iconView setFrame:CGRectMake([[self.checkNameLbs lastObject]frame].origin.x + 52 + self.roundUnselect.size.width, [[self.checkNameLbs lastObject]frame].origin.y + ([[self.checkNameLbs lastObject]frame].size.height + 10)*(i+1) + 4, iconImage.size.width, iconImage.size.height)];
        [self.backScrollV addSubview:iconView];
        [self.controlWillClears addObject:iconView];
        
        UILabel *childLabel = [UILabel new];
        NSString *string = [array objectAtIndex:i];
        childLabel.text = [NSString stringWithFormat:@"%@：",string];
        childLabel.font = [UIFont systemFontOfSize:26];
        CGSize mySize = [childLabel.text sizeWithFont:childLabel.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];
        childLabel.frame = CGRectMake([[self.checkNameLbs lastObject]frame].origin.x + self.roundUnselect.size.width + 52 + iconImage.size.width + 10, [[self.checkNameLbs lastObject]frame].origin.y + ([[self.checkNameLbs lastObject]frame].size.height + 10)*(i+1), mySize.width, mySize.height);
        [self.backScrollV addSubview:childLabel];
        [self.controlWillClears addObject:childLabel];
    }
    [self.selectBtnArr addObject:controlsArr];
}

- (void)selectBtns:(id)sender//运作部
{
    UIButton *btn = (UIButton*)sender;
    for (int i = 0;i<self.selectBtnArr.count;i++)
    {
        NSArray *btnArr = [self.selectBtnArr objectAtIndex:i];
        if ([btnArr containsObject:btn])
        {
            for (int j = 0;j<btnArr.count;j++)
            {
                UIButton *seleBtn = [btnArr objectAtIndex:j];
                [seleBtn setImage:self.roundUnselect forState:UIControlStateNormal];
                if (btn == [btnArr objectAtIndex:j])
                {
                    [seleBtn setImage:self.roundSelect forState:UIControlStateNormal];
                    [self.sendCheckDatas replaceObjectAtIndex:i withObject:@{@"checkId": [checkIds objectAtIndex:i],@"isNormal":[NSString stringWithFormat:@"%d",j],@"checkRemark":@""}];
                }
                if (j == 0)
                {
                    [[UIApplication sharedApplication].keyWindow endEditing:YES];
                }
            }
        }
    }
    NSLog(@"------%@--------",self.sendCheckDatas);
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.myTableView)
    {
        return self.floorNames.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (tableView == self.myTableView)
    {
        self.mycell.textLabel.text = [self.floorNames objectAtIndex:indexPath.row];
        return self.mycell;
    }
    return nil;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    [self hiddenAll];
    if (tableView == self.myTableView)
    {
        [UIView animateWithDuration:.9 animations:^
         {
             self.backScrollV.contentSize = CGSizeMake(0, 0);
         }];
        
        [self showUIWithArray:self.allShowDataArr andFloorId:[self.floorIds objectAtIndex:indexPath.row]];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    for (int i = 0; i < sendControls.count; i ++)
    {
        NSDictionary *controlDic = [sendControls objectAtIndex:i];
        NSArray *tfs = [controlDic objectForKey:@"childControls"];
        for (int j = 0; j < tfs.count; j ++)
        {
            id tf = [tfs objectAtIndex:j];
            NSDictionary *sendChildDic = [self.sendCheckDatas objectAtIndex:i];
            NSString *isNormal = [sendChildDic valueForKey:@"isNormal"];
            if (tf == textField && [isNormal integerValue]!= 0)
            {
                return YES;
            }
        }
    }
    return 0;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    for (int i = 0; i < sendControls.count; i ++)
    {
        NSDictionary *controlDic = [sendControls objectAtIndex:i];
        
        NSString *checkId = [controlDic valueForKey:@"checkId"];
        NSArray *tfs = [controlDic objectForKey:@"childControls"];
        for (int j = 0; j < tfs.count; j ++)
        {
            id tf = [tfs objectAtIndex:j];
            if (tf == textField)
            {
                NSDictionary *sendChildDic = [self.sendCheckDatas objectAtIndex:i];
                NSString *isNormal = [sendChildDic valueForKey:@"isNormal"];
                NSString *remark = [textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [self.sendCheckDatas replaceObjectAtIndex:i withObject:@{@"checkId": checkId,@"isNormal":isNormal,@"checkRemark":remark}];
            }
        }
    }
    NSLog(@"======%@=======",self.sendCheckDatas);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
